﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace BanaToys.InfoSys.Web.ApiCall
{
    /// <summary>
    /// 
    /// </summary>
    public class Help
    {
        /// <summary>
        /// 获得文件MD5值
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="md5Hex_or_Err"></param>
        /// <returns></returns>
        public static bool GetFileMD5(string fileName, out string md5Hex_or_Err)
        {
            //
            md5Hex_or_Err = null;

            //MD5值
            try
            {
                StringBuilder sb = new StringBuilder();
                //FileStream file = new FileStream(fileName, FileMode.Open);
                using (FileStream file = new FileStream(fileName, FileMode.Open))
                {
                    MD5 md5 = new MD5CryptoServiceProvider();
                    byte[] retVal = md5.ComputeHash(file);
                    file.Close();
                    for (int i = 0; i < retVal.Length; i++)
                    {
                        sb.Append(retVal[i].ToString("x2"));
                    }
                }
                md5Hex_or_Err = sb.ToString();
            }
            catch (Exception ex)
            {
                //throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);

                md5Hex_or_Err = "错误:" + ex.Message;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="fileBytes"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static bool GetHttpPostedFile(HttpPostedFile postedFile, out byte[] fileBytes, out string message)
        {
            //
            fileBytes = null;
            message = "";

            //
            if (postedFile == null)
            {
                message = "上传文件为空";
                return false;
            }

            int size = postedFile.ContentLength;
            Stream input_sm = postedFile.InputStream;

            #region 方法1

            //byte[] bytes = new byte[size];
            //
            //if (!sm.CanRead)
            //{
            //    message = "InputStream not CanRead";
            //    return false;
            //}
            //int bytes_read = sm.Read(bytes, 0, bytes.Length);
            //if (!sm.CanSeek)
            //{
            //    message = "InputStream not CanSeek";
            //    return false;
            //}
            //sm.Seek(0, SeekOrigin.Begin);

            //.net 4.0
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    input_sm.Seek(0, SeekOrigin.Begin);
            //    input_sm.CopyTo(ms);//.net 4
            //    byte[] array = ms.GetBuffer();
            //}

            #endregion

            #region 方法2
            using (BinaryReader br = new BinaryReader(input_sm))
            {
                fileBytes = br.ReadBytes(size);
            }
            #endregion

            //
            return true;
        }

        /// <summary>
        /// 字节数组的MD5
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static string GetBytesMD5(byte[] buffer)
        {
            StringBuilder sb = new StringBuilder();
            //byte[] buffer = Encoding.UTF8.GetBytes(str);
            using (MD5 md5 = MD5.Create())
            {
                byte[] md5Bytes = md5.ComputeHash(buffer);
                for (int i = 0; i < md5Bytes.Length; i++)
                {
                    sb.Append(md5Bytes[i].ToString("x2"));//X2时，生成字母大写MD5
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToString(object obj)
        {
            //
            if (obj == null) return string.Empty;
            StringBuilder sb = new StringBuilder();

            //
            Type t = obj.GetType();//获得该类的Type

            //System.Reflection.PropertyInfo
            PropertyInfo[] pp = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);

            //再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了
            foreach (PropertyInfo pi in pp)
            {
　　            object value1 = pi.GetValue(obj, null);//用pi.GetValue获得值
　　            string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
　　            //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
　　            //if(value1.GetType() == typeof(int)){}//进行你想要的操作
                sb.AppendLine(string.Format("{0}={1}",name,value1));
            }

            return sb.ToString();
        }

        #region timestamp

        /// <summary>
        /// 
        /// </summary>
        private static DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static DateTime TimeStampToUtcTime(long timestamp)
        {
            //13位毫秒,乘10000,
            string s = timestamp.ToString();
            if (s.Length < 13)
            {
                s = s.PadRight(13, '0');
                timestamp = long.Parse(s);
            }
            else if (s.Length > 13)
            {
                s = s.Substring(0, 13);
                timestamp = long.Parse(s);
            }
            //
            TimeSpan ts = new TimeSpan(timestamp * 10000);
            return dt1970.Add(ts);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="utcTime"></param>
        /// <returns></returns>
        public static long UtcTimeToTimeStamp(DateTime utcTime)
        {
            return Convert.ToInt64((utcTime - dt1970).TotalMilliseconds);
        }

        #endregion

    }
}